package com.yixing.demo.interceptor;

import com.yixing.demo.component.JwtClass;
import com.yixing.demo.constants.Constants;
import com.yixing.demo.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constants.USER_TOKEN_HEADER);
        log.info("从前端传来的token为：" + token + request.getRequestURL().toString());
        Claims body = JwtClass.parseToken(token);
        if(body != null) {
            Integer userId = body.get(Constants.USER_ID, Integer.class);
            String username = body.get(Constants.USER_NAME, String.class);
            User user = new User();
            user.setUserId(userId);
            user.setUsername(username);
            log.info("" + userId + username);
            HttpSession session = request.getSession(true);
            session.setAttribute(Constants.USER_SESSION, user);
            return true;
        }else {
            log.info("40140140140114444444444444444444444444444444444444444444444444444444444444444444444444444444");
            response.setStatus(401);
            return false;
        }
    }
}
